package com.qianlou.config;

import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvEntry;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
@Component
public class DotenvPropertySource implements EnvironmentPostProcessor {

    public static final String ENV_FILE_KEY_NAME = "env.file.name";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        try {
            // 1. 从classpath加载环境变量文件
            Path tempEnvFile = createTempFileFromResource("classpath:" + System.getenv(ENV_FILE_KEY_NAME));
            if (tempEnvFile == null) {
                throw new IllegalStateException("找不到文件，请确认其位于 src/main/resources 目录下");
            }
            // 2. 使用dotenv-java解析临时文件
            Dotenv dotenv = Dotenv.configure()
                    .directory(tempEnvFile.getParent().toString())
                    .filename(tempEnvFile.getFileName().toString())
                    .load();
            StringEncryptor stringEncryptor = JasyptConfig.getEncryptor();
            // 3. 将 .env 中的键值对添加进 Spring Environment
            for (DotenvEntry entry : dotenv.entries(Dotenv.Filter.DECLARED_IN_ENV_FILE)) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (StringUtils.isBlank(value)) {
                    continue;
                }
                if (key.startsWith("NOT_")) {
                    environment.getSystemProperties().put(key.substring(4), value);
                } else {
                    //加密配置值
                    environment.getSystemProperties().put(key, stringEncryptor.encrypt(value));
                }
            }
        } catch (Exception e) {
            log.error("Error loading file: {}", e.getMessage());
        }
    }

    /**
     * 从 classpath 中读取文件并创建临时文件
     */
    private Path createTempFileFromResource(String resourcePath) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(resourcePath.replace("classpath:", ""));
        if (!classPathResource.exists()) {
            return null;
        }
        // 创建临时文件
        Path tempFile = Files.createTempFile("dotenv-", ".tmp");
        tempFile.toFile().deleteOnExit();
        // 复制内容到临时文件
        try (InputStream is = classPathResource.getInputStream()) {
            Files.write(tempFile, is.readAllBytes());
        }
        return tempFile;
    }
}
